package com.tianruan.dc.modules.sys.user.api;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tianruan.dc.common.base.controller.BaseController;
import com.tianruan.dc.common.constant.GlobalExceptionEnum;
import com.tianruan.dc.common.utils.PageUtils;
import com.tianruan.dc.common.utils.encryption.Md5Utils;
import com.tianruan.dc.common.utils.response.VResponse;
import com.tianruan.dc.modules.sys.user.entity.db.RoleDO;
import com.tianruan.dc.modules.sys.user.entity.db.UserDO;
import com.tianruan.dc.modules.sys.user.entity.dto.UserDTO;
import com.tianruan.dc.modules.sys.user.entity.vo.UserVO;
import com.tianruan.dc.modules.sys.user.service.IUserRoleService;
import com.tianruan.dc.modules.sys.user.service.IUserService;
import com.tianruan.dc.modules.sys.user.utils.UserUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;


@RestController
@RequestMapping("/api/sys/user")
@Slf4j
@Api(description = "用户接口")
public class UserController extends BaseController {

    @Autowired
    private IUserService userService;


    @Autowired
    private IUserRoleService userRoleService;


    @ApiOperation(value = "获取用户", notes = "分页获取用户")
    @GetMapping
    @PreAuthorize("hasAnyAuthority('admin')")
    public VResponse<PageUtils> pageUser(Page page,
                                         @RequestParam(value = "officeId", required = false) String officeId,
                                         @RequestParam(value = "no", required = false) String no,
                                         @RequestParam(value = "username", required = false) String username,
                                         @RequestParam(value = "name", required = false) String name,
                                         @RequestParam(value = "phone", required = false) String phone,
                                         @RequestParam(value = "email", required = false) String email,
                                         @RequestParam(value = "roleId", required = false) List<String> roleIdList,
                                         @RequestParam(value = "current", defaultValue = "1") Long current,
                                         @RequestParam(value = "pageSize", defaultValue = "20") Long pageSize){

        page.setCurrent(current);
        page.setSize(pageSize);
        return VResponse.success(new PageUtils(userService.pageUser(page, officeId, no, username, name, phone, email, roleIdList)));
    }

    /**
     * 获取学生列表
     * @param page
     * @param userDTO
     * @return
     */
    @GetMapping("/student")
    @PreAuthorize("hasAnyAuthority('admin')")
    public VResponse<PageUtils> pageUser(Page page,
                                         UserDTO userDTO){

        page.setCurrent(userDTO.getCurrent());
        page.setSize(userDTO.getPageSize());
        return VResponse.success(new PageUtils(userService.pageStudent(page, userDTO.getOfficeId(), userDTO.getNo(), userDTO.getName(), userDTO.getPhone(), userDTO.getEmail())));
    }

    /**
     * 搜索教师
      */
    @GetMapping("/search/teacher")
    @PreAuthorize("hasAnyAuthority('admin', 'officeAdmin', 'student', 'teacher')")
    public VResponse<PageUtils> searchTeacher(Page page,
                                         UserDTO userDTO){
        return VResponse.success(userService.searchTeacher(userDTO));
    }

    /**
     * 搜索教师
     */
    @GetMapping("/search/student")
    @PreAuthorize("hasAnyAuthority('admin', 'officeAdmin', 'student', 'teacher')")
    public VResponse<PageUtils> searchStudent(Page page,
                                              UserDTO userDTO){
        return VResponse.success(userService.searchStudentByStudent(userDTO));
    }


    /**
     * 获取专家列表
     * @param page
     * @param userDTO
     * @return
     */
    @GetMapping("/office/expert")
    @PreAuthorize("hasAnyAuthority('officeAdmin')")
    public VResponse<PageUtils> pageOfficeExpert(Page page,
                                           UserDTO userDTO){
        UserDTO currentUser = UserUtils.getUser();
        userDTO.setOfficeId(currentUser.getOfficeId());
        return VResponse.success(new PageUtils(userService.findExpertList(userDTO)));
    }

    /**
     * 获取专家列表
     * @param page
     * @param userDTO
     * @return
     */
    @GetMapping("/office/dc/expert")
    @PreAuthorize("hasAnyAuthority('officeAdmin')")
    public VResponse<PageUtils> pageDCOfficeExpert(Page page,
                                                 UserDTO userDTO){
        UserDTO currentUser = UserUtils.getUser();
        userDTO.setOfficeId(currentUser.getOfficeId());
        return VResponse.success(new PageUtils(userService.findDCExpertList(userDTO)));
    }

    /**
     * 获取专家列表
     * @param page
     * @param userDTO
     * @return
     */
    @GetMapping("/expert")
    @PreAuthorize("hasAnyAuthority('admin')")
    public VResponse<PageUtils> pageExpert(Page page,
                                         UserDTO userDTO){
        return VResponse.success(new PageUtils(userService.findExpertList(userDTO)));
    }


    /**
     * 获取当前用户学院学生列表
     * @param page
     * @param userDTO
     * @return
     */
    @GetMapping("/office/student")
    @PreAuthorize("hasAnyAuthority('officeAdmin')")
    public VResponse<PageUtils> pageOfficeUser(Page page,
                                         UserDTO userDTO){
        UserDTO user = UserUtils.getUser();

        page.setCurrent(userDTO.getCurrent());
        page.setSize(userDTO.getPageSize());
        return VResponse.success(new PageUtils(userService.pageStudent(page, user.getOfficeId(), userDTO.getNo(), userDTO.getName(), userDTO.getPhone(), userDTO.getEmail())));
    }

    @ApiOperation(value = "获取用户", notes = "根据用户id获取用户")
    @GetMapping("/{id}")
    public ResponseEntity getUser(@PathVariable("id")String id){
        UserVO userRoleById = userService.getUserRoleById(id);
        return ResponseEntity.ok(userRoleById);
    }

    @GetMapping("searchNo")
    public VResponse<List<UserVO>> searchNo(@RequestParam("no") String no) {
        QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("no", no)
                    .or()
                    .like("su.name", no);
        queryWrapper.last("limit 50");
        List<UserVO> userVOS = userService.serachStudent(queryWrapper);
        return VResponse.success(userVOS);
    }


    @GetMapping("searchTeacher")
    public VResponse<List<UserVO>> searchTeacher(UserDTO userDTO) {

        userDTO.setPageSize(50);
        List<UserVO> userVOS = userService.searchTeacherList(userDTO);
        return VResponse.success(userVOS);
    }

    @ApiOperation(value = "添加用户", notes = "添加用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户标识", required = true, paramType = "query", dataType = "String")
    })
    /**
     * 添加用户
     */
    @PostMapping
    public ResponseEntity insertUser(@RequestBody UserDTO userDTO){
        return ResponseEntity.ok(userService.insertUser(userDTO));
//        return null;
    }


    /**
     * 更新用户信息
     * @param id
     * @param userDTO
     * @return
     */
    @PutMapping("/{id}")
    public ResponseEntity updateUser(@PathVariable("id")String id,
                                     @RequestBody UserDTO userDTO){
        return ResponseEntity.ok(userService.updateUser(id, userDTO));
    }

    /**
     * 更新用户角色
     * @param id            用户id
     * @param roleIdList    用户角色列表
     * @return
     */
    @PutMapping("/role")
    public VResponse<Object> updateUserRole(@RequestParam("id") String id,
                                            @RequestParam(value = "roleId", required = false) List<String> roleIdList){
        userRoleService.insertUserRole(id, roleIdList);
        return VResponse.success("修改用户角色成功");
    }


    @GetMapping("/self")
    public VResponse<UserVO> self(){
        UserDTO userDTO = UserUtils.getUser();
        UserVO userInfo = new UserVO();
        BeanUtils.copyProperties(userDTO, userInfo);
        return VResponse.success(userInfo);
    }

    /**
     * 获取当前用户信息
     * @return
     */
    @GetMapping("/info")
    public VResponse<UserVO> userInfo(){
        UserDTO user = UserUtils.getUser();
        UserVO userRoleById = userService.getUserRoleById(user.getId());
        List<RoleDO> roles = userRoleById.getRoles();
        List<String> roleIds = new ArrayList<>();
        for (RoleDO roleDO : roles) {
            roleIds.add(roleDO.getId());
        }
        return VResponse.success(userRoleById);
    }

    /**
     * 获取当前用户信息
     * @return
     */
    @GetMapping("/currentUser")
    public VResponse<UserVO> currentUser(){
        return userInfo();
    }

    /**
     * 修改密码
     * @param oldPassword
     * @param newPassword
     */
    @PutMapping("/modify/password")
    @ApiOperation(value = "修改密码", notes = "修改密码")
    public VResponse<Object> modifyPassword(@RequestParam("oldPassword") String oldPassword,
                                            @RequestParam("newPassword") String newPassword) {
        UserDTO user = UserUtils.getUser();
        Boolean equals = userService.equalsPassword(user.getId(), oldPassword);
        if (equals) {
            userService.modifyPassword(user.getId(), newPassword);
            return VResponse.result(GlobalExceptionEnum.MODIFY_PASSWORD_SUCCESS);
        } else {
            return VResponse.result(GlobalExceptionEnum.ERROP_PASSWORD);
        }
    }

    /**
     * 重置密码
     * @param id
     */
    @PutMapping("/reset/password")
    @ApiOperation(value = "重置密码", notes = "重置密码")
//    @PreAuthorize("hasAnyAuthority('admin', 'officeAdmin')")
    public VResponse<Object> modifyPassword(@RequestParam("id") String id) {
        UserDTO currentUser = UserUtils.getUser();
        UserDO user = userService.getById(id);
        List<String> roleIds = currentUser.getRoleIds();

        if (user == null) {
            return VResponse.error(1000, "重置密码失败，用户不存在");
        }
        String no = user.getNo();
        userService.modifyPassword(id, no);
        return VResponse.result(GlobalExceptionEnum.RESET_PASSWORD_SUCCESS);
    }

    @PostMapping("/import/user/student")
    public void importUser(@RequestParam("file") MultipartFile file) {
        userService.importStudent(file);
    }

    @PostMapping("/import/teacher")
    public void importTeacher(@RequestParam("file") MultipartFile file) {
        userService.importTeacher(file);
    }

    @GetMapping("/updatePassword")
    public void updatePassword() {
        QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("enrollment_year", "2022");
        queryWrapper.eq("type", "1");
        List<UserDO> list = userService.list(queryWrapper);
        for(UserDO userDO: list) {
            userDO.setPassword(Md5Utils.entrypt(userDO.getUsername()));
        }
        userService.updateBatchById(list);
        System.out.println();
    }

    private  boolean isRowEmpty(Row row){
        for (int c = row.getFirstCellNum(); c < row.getLastCellNum(); c++) {
            Cell cell = row.getCell(c);
            if (cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK)
                return false;
        }
        return true;
    }
}
